package com.chookss.home.other;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chookss.R;
import com.chookss.Urls;
import com.chookss.WebCommonActivity;
import com.chookss.base.StaticClass;
import com.chookss.base.X5WebView;
import com.chookss.home.adapter.NoticeListsAdapter;
import com.chookss.home.entity.NoticeListEntity;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.wxapi.ShareActivity;
import com.google.gson.reflect.TypeToken;
import com.gyf.immersionbar.ImmersionBar;
import com.gyf.immersionbar.components.ImmersionFragment;
import com.gyf.immersionbar.components.SimpleImmersionFragment;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;

@SuppressLint("ValidFragment")
public class AbilityAnalyzeBaseFragment extends ImmersionFragment {

    public Activity mContext;
    Unbinder unbinder;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.flTop)
    FrameLayout flTop;
    @BindView(R.id.webView)
    X5WebView webView;
    @BindView(R.id.ivBack)
    ImageView ivBack;
    @BindView(R.id.llBottom)
    LinearLayout llBottom;
    @BindView(R.id.tvSure)
    TextView tvSure;
    @BindView(R.id.rlRight)
    RelativeLayout rlRight;
    @BindView(R.id.ivRight)
    ImageView ivRight;
    @BindView(R.id.gif_view)
    GifImageView gifView;
    private GifDrawable gifDrawable = null;
    private String url, title, userName;
    private boolean isPress = false;//是否可以查看个人能力分析
    private boolean isFull = false;//是否全屏
    private boolean isPersonalAbility = false;//是否个人能力分析页面  一定要全屏的

    public AbilityAnalyzeBaseFragment() {

    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = (Activity) context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_web_ability, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onLazyAfterView() {
        super.onLazyAfterView();
        init();
    }

    private void init() {
        //顶部状态栏 处理
        url = NavigationTools.getAllUrl2(mContext, Urls.getCapacityAnalysisCapacity) + "&employeeCode=" + new ShareUtils().getString(mContext, StaticClass.EMPLOYEECODE, "");
        title = "个人能力分析";
        ivBack.setImageResource(R.drawable.icon_back_black);
        int statusBarHeight = Utils.getStatusBarHeight(mContext);
        RelativeLayout.LayoutParams webViewAllParams = (RelativeLayout.LayoutParams) webView.getLayoutParams();
        webViewAllParams.setMargins(0, statusBarHeight + Utils.dip2px(mContext, 44), 0, 0);
        webView.setLayoutParams(webViewAllParams);
        RelativeLayout.LayoutParams topAllParams = (RelativeLayout.LayoutParams) flTop.getLayoutParams();
        topAllParams.setMargins(0, statusBarHeight, 0, 0);
        flTop.setLayoutParams(topAllParams);
        flTop.setBackgroundColor(getResources().getColor(R.color.white));
        tvTitle.setText(title);
        try {
            llBottom.setVisibility(View.VISIBLE);
            gifDrawable = new GifDrawable(getResources(), R.drawable.grnl_gif);
            gifDrawable.setLoopCount(1);
            gifView.setBackground(gifDrawable);
            Observable.timer(gifDrawable.getDuration() - 1000, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<Long>() {
                        @Override
                        public void accept(Long aLong) {
                            if (tvSure != null) {
                                tvSure.setPressed(true);
                                isPress = true;
                            }
                        }
                    });
            tvSure.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (isPress) {
                        llBottom.setVisibility(View.GONE);
                    } else {
                        MyToast.show("个人能力分析中");
                    }


                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        ivRight.setBackgroundResource(R.drawable.icon_wenh_42);
        rlRight.setOnClickListener(v -> {
            String url = NavigationTools.getAllUrl2(mContext, Urls.webBaseUrl + "capacityAnalysis.html#/relation?");
            webView.loadUrl(url);
        });
        webView.loadUrl(url);
        webView.setWebChromeClient(new WebChromeClient() {
            //For Android  >= 5.0
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                return true;
            }

            //For Android  >= 4.1
            public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView webView, String s) {
                super.onReceivedTitle(webView, s);
                KLog.i(s + "---s" + webView.getTitle());
            }

            View myVideoView;
            IX5WebChromeClient.CustomViewCallback callback;

            /**
             * 全屏播放配置
             */
            @Override
            public void onShowCustomView(View view,
                                         IX5WebChromeClient.CustomViewCallback customViewCallback) {
                //此处是把webview的父布局替换为view，此view是全屏播放时候的界面（tbs的默认实现）
                ViewGroup viewGroup = (ViewGroup) webView.getParent();
                viewGroup.removeView(webView);
                // 设置背景色为黑色
                view.setBackgroundColor(getResources().getColor(R.color.black));
                viewGroup.addView(view);
                myVideoView = view;
                callback = customViewCallback;
            }

            @Override
            public void onHideCustomView() {
                if (callback != null) {
                    callback.onCustomViewHidden();
                    callback = null;
                }
                if (myVideoView != null) {
                    ViewGroup viewGroup = (ViewGroup) myVideoView.getParent();
                    viewGroup.removeView(myVideoView);
                    viewGroup.addView(webView);
                }
            }
        });
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
                // TODO Auto-generated method stub
                return super.shouldOverrideKeyEvent(view, event);
            }

            @Override
            public boolean shouldOverrideUrlLoading(final WebView view,
                                                    final String url) {
                return super.shouldOverrideUrlLoading(webView, url);
            }// 重写点击动作,用webview载入

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
            }

            @Override
            public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
                // 不要使用super，否则有些手机访问不了，因为包含了一条 handler.cancel()
                // super.onReceivedSslError(view, handler, error);
                // 接受所有网站的证书，忽略SSL错误，执行访问网页
                sslErrorHandler.proceed();
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                if (tvTitle == null || rlRight == null || view == null) {
                    return;
                }
                KLog.i(view.getTitle() + "-----" + view.getUrl());
                if (view.getUrl().contains("capacityAnalysis.html#/capacity")) {
                    if (Utils.isNull(userName)) {
                        tvTitle.setText("个人能力分析");
                    } else {
                        tvTitle.setText(userName + "的能力分析");
                    }
                    rlRight.setVisibility(View.GONE);
                    ivBack.setVisibility(View.GONE);
                } else if (view.getUrl().contains("capacityAnalysis.html#/grad")) {
                    //成长历程
                    tvTitle.setText("段位");
                    rlRight.setVisibility(View.VISIBLE);
                    ivBack.setVisibility(View.VISIBLE);
                } else if (view.getUrl().contains("capacityAnalysis.html#/relation")) {
                    //成长历程
                    tvTitle.setText("关系");
                    rlRight.setVisibility(View.GONE);
                    ivBack.setVisibility(View.VISIBLE);
                } else if (view.getUrl().contains("capacityAnalysis.html#/detail")) {
                    //成长历程
                    tvTitle.setText("明细");
                    rlRight.setVisibility(View.GONE);
                    ivBack.setVisibility(View.VISIBLE);
                }else{
                    ivBack.setVisibility(View.VISIBLE);
                }
            }

        });
    }

    private void goBack() {
        //按下返回键或者左上角返回箭头的操作
        if (null == webView) return;
        if (webView.canGoBack()) {
            webView.goBack();
        }
    }
    @OnClick(R.id.ivBack)
    public void onClick() {
        goBack();
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        if (gifDrawable != null) {
            gifDrawable.recycle();
        }
    }

    @Override
    public void initImmersionBar() {
        ImmersionBar.with(getActivity())
                .transparentStatusBar()  /*透明状态栏，不写默认透明色*/  /*状态栏字体是深色，不写默认为亮色*/
                .statusBarDarkFont(true)
                .flymeOSStatusBarFontColor(R.color.grey_3)  /*修改flyme OS状态栏字体颜色*/
                .keyboardEnable(false).navigationBarEnable(false)
                .init();
    }
}
